import editForm from "../form.vue";
import runJobForm from "../runJobForm.vue";
import { message } from "@/utils/message";
import {
  saveJob,
  deleteAppInfo,
  getJobInfoPage,
  runJob,
  modifyJobStatus
} from "@/api/job";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw } from "vue";
import type { FormItemProps, RunJobRequest } from "../utils/types";
import { deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { toBackendPageObj, toFrontendPageObj } from "@/api/utils";
import { formatDate } from "@/utils/formatter";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/utils/hooks";

export function useAppInfo() {
  const form = reactive({
    appId: "",
    jobName: "",
    jobDescription: "",
    status: ""
  });

  const formRef = ref();
  const runJobFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    background: true,
    small: false
  });

  const columns: TableColumnList = [
    {
      label: "任务名称",
      prop: "jobName",
      width: 150,
      align: "left"
    },
    {
      label: "描述",
      prop: "jobDescription",
      minWidth: 250
    },
    {
      label: "定时信息",
      prop: "timeExpression",
      cellRenderer: ({ row }) => (
        <div style="display: flex; align-items: left">
          <iconify-icon-online icon="ep:timer" />
          <span style="margin-left: 10px">
            {row.timeExpressionType} {row.timeExpression}
          </span>
        </div>
      ),
      minWidth: 120
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={"NORMAL"}
          inactive-value={"INACTIVE"}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "描述",
      prop: "description",
      minWidth: 220
    },
    {
      label: "创建时间",
      minWidth: 120,
      prop: "createTime",
      formatter: ({ createTime }) => formatDate(createTime)
    },
    {
      label: "创建人",
      minWidth: 80,
      prop: "createdByUsername"
    },
    {
      label: "更新时间",
      minWidth: 120,
      prop: "updateTime",
      formatter: ({ updateTime }) => formatDate(updateTime)
    },
    {
      label: "更新人",
      minWidth: 80,
      prop: "updatedByUsername"
    },
    {
      label: "操作",
      fixed: "right",
      width: 320,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    pagination.currentPage = val;
    onSearch();
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const data = await getJobInfoPage({
      ...toRaw(form),
      ...toBackendPageObj(pagination)
    });
    dataList.value = data.records;
    toFrontendPageObj(data, pagination);

    setTimeout(() => {
      loading.value = false;
    }, 300);
  }

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === "INACTIVE" ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.jobName
      }</strong>应用吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        modifyJobStatus(row)
          .then(() => {
            setTimeout(() => {
              switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                  loading: false
                }
              );
              message(
                `已${row.status === "INACTIVE" ? "停用" : "启用"}${row.jobName}`,
                {
                  type: "success"
                }
              );
            }, 300);
          })
          .catch(error => {
            console.log("error", error);
            message(error.message, {
              type: "error"
            });
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
          });
      })
      .catch(error => {
        console.log(error);
      });
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}任务信息`,
      props: {
        formInline: {
          id: row?.id ?? "",
          appId: row?.appId ?? "",
          jobName: row?.jobName ?? "",
          jobDescription: row?.jobDescription ?? "",
          jobParams: row?.jobParams ?? "",
          timeExpressionType: row?.timeExpressionType ?? "",
          timeExpression: row?.timeExpression ?? "",
          processorType: row?.processorType ?? "",
          processorInfo: row?.processorInfo ?? "",
          status: row?.status ?? "NORMAL",
          instanceTimeLimit: row?.instanceTimeLimit ?? 0,
          retryTimes: row?.retryTimes ?? 0,
          lifecycleRange: row?.lifecycleRange ?? [],
          logConfig: row?.logConfig ?? {}
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function save() {
          if (title === "新增") {
            saveJob(curData)
              .then(() => {
                message(`您${title}了任务名称为${curData.jobName}的这条数据`, {
                  type: "success"
                });
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              })
              .catch(error => {
                console.log("error", error);
                message(error.message, {
                  type: "error"
                });
              });
          } else {
            saveJob(curData)
              .then(() => {
                message(
                  `您${title}了业务域名称为${curData.jobName}的这条数据`,
                  {
                    type: "success"
                  }
                );
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              })
              .catch(error => {
                console.log("error", error);
                message(error.message, {
                  type: "error"
                });
              });
          }
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              save();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              save();
            }
          }
        });
      }
    });
  }

  function handleRunJob(row) {
    addDialog({
      title: `运行任务`,
      props: {
        formInline: {
          jobId: row?.id ?? "",
          appId: row?.appId ?? "",
          instanceParams: row?.jobParams ?? ""
        }
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(runJobForm, { ref: runJobFormRef }),
      beforeSure: (done, { options }) => {
        const FormRef = runJobFormRef.value.getRef();
        const curData = options.props.formInline as RunJobRequest;

        function doRunJob() {
          runJob(curData)
            .then(() => {
              message(`任务${row.jobName}已被运行`, {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(error => {
              console.log("error", error);
              message(error.message, {
                type: "error"
              });
            });
        }

        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            doRunJob();
          }
        });
      }
    });
  }

  function handleDelete(row) {
    deleteAppInfo(row.id).then(() => {
      message(`您删除了应用名称为${row.jobName}的这条数据`, {
        type: "success"
      });
      onSearch();
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改业务域 */
    openDialog,
    /** 删除业务域 */
    handleDelete,
    handleRunJob,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
